package com.ttl.bc.ap.invoice.action;


import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import com.ttl.bc.ap.invoice.bean.BCAPInvoiceBean;
import com.ttl.bc.ap.invoice.bo.BCAPInvoiceBO;
import com.ttl.bc.ap.invoice.bo.BCAPInvoiceDAO;
import com.ttl.bc.ap.invoice.bo.BCAPInvoiceReportBO;




import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;

public class BCAPInvoiceAction extends DispatchAction {
	
	public ActionForward cancel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		BCAPInvoiceBO bo = new BCAPInvoiceBO();		
		BCAPInvoiceBean inv = bo.findInv(form, request);
				
		request.setAttribute("inv", inv);				
//		request.setAttribute("countId", results.size());		
		
		return mapping.findForward("success_cancel");		
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :delete");
		
		BCAPInvoiceBO bo = new BCAPInvoiceBO();						
		if (bo.delete(form, request, response)==true) {			
			return mapping.findForward("success_delete");
		}else {
			//ทำ map กับการ fail_add
			return mapping.findForward("fail_delete");
		}
	}	
	
	public ActionForward invFind(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :invFind ");
	
		DynaActionForm dynaForm = (DynaActionForm)form;
		@SuppressWarnings("unused")
		String docNo2 = ""+dynaForm.getString("docNo2");
		String itemFind = ""+dynaForm.getString("itemFind");
		
		if(itemFind!=null) {
			itemFind = itemFind.trim(); 
			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");		//แปลงให้ค้นหาภาษาไทยได้
		}		
		request.setAttribute("itemFind", itemFind);		
		
		String hql = "FROM BCAPInvoiceBean " +
				" WHERE docNo like '%"+itemFind+"%' and  " +
				" (docNo like 'BCS%' or docNo like 'CRS%' or docNo like 'CMD%' )"+
				" ORDER BY docNo";

		System.out.println(hql);
		Page.setPage(request, hql);
		
		return mapping.findForward("success_invFind");
	}
	
	public ActionForward printINV(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {

		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :printINV");		
				
		return mapping.findForward("blank_printinv");
	}
	
	public ActionForward blank_po(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
				
		String user 	 = (String)request.getSession().getAttribute("userName");				
		@SuppressWarnings("unused")
		String preDocNo  = (String)request.getSession().getAttribute("preDocNo");				
						
		String docNo     = CommonUtils.getMaxBCPurchaseOrderDocNo("PO1-");
		
		request.getSession().setAttribute("userName", user);
		request.getSession().setAttribute("docNo", docNo);		
		
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :blank");
		
		return mapping.findForward("blank_po");
	}
		
	@SuppressWarnings("unchecked")
	public ActionForward findPOSelectedOLD(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :findPOSelected");
				
		BCAPInvoiceBO bo = new BCAPInvoiceBO();
		ArrayList results = (ArrayList)bo.find(form, request);
		BCAPInvoiceForm fullForm = (BCAPInvoiceForm)bo.getBCAPInvoiceForm(results);		
		
		request.getSession().setAttribute("userName", user);
		request.setAttribute("fullForm", fullForm);		
		
		return mapping.findForward("blank_showData");
	}
		
	
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :add ok");
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		
		if (dao.add(form, request, response)) {							
			return mapping.findForward("success_add");
		}else {
			//ทำ map กับการ fail_add
			return mapping.findForward("fail_add");
		}
		
//แบบเดิม ใช้่ add invoice ใน BO		
//		BCAPInvoiceBO bo = new BCAPInvoiceBO();		
//		if (bo.add(form, request, response)==true) {							
//			return mapping.findForward("success_add");
//		}else {
//			//ทำ map กับการ fail_add
//			return mapping.findForward("fail_add");
//		}
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :update ok");
		
		BCAPInvoiceBO bo = new BCAPInvoiceBO();						
		if (bo.update(form, request, response)==true) {							
			return mapping.findForward("success_update");
		}else {
			//ทำ map กับการ fail_update
			return mapping.findForward("fail_update");
		}
	}	
	public ActionForward update2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :update ok");
		
		BCAPInvoiceBO bo = new BCAPInvoiceBO();						
		if (bo.update2(form, request, response)==true) {							
			return mapping.findForward("success_update2");
		}else {
			//ทำ map กับการ fail_update
			return mapping.findForward("fail_update2");
		}
	}	
	public ActionForward showFind(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :showFind");
		
/*		BCAPInvoiceBO bo = new BCAPInvoiceBO();
		ArrayList results = (ArrayList)bo.find(request);
		
		request.getSession().setAttribute("results", results);	*/					
		new BCAPInvoiceBO().showFind(request);
		return mapping.findForward("success_showFind2");
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :edit ");
			
		new BCAPInvoiceBO().setForm(request);
		
		return mapping.findForward("blank_edit");
	}	

	public ActionForward edit2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		BCAPInvoiceBO bo = new BCAPInvoiceBO();		
		BCAPInvoiceBean inv = bo.findInv(form, request);
				
		request.setAttribute("inv", inv);				
//		request.setAttribute("countId", results.size());		
		
		return mapping.findForward("success_edit2");		
	}	
	
	public ActionForward moreDetailsShow(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :moreDetailsShow ");
		
		new BCAPInvoiceBO().setMoreDetailsForm(request);
		
		return mapping.findForward("moreDetailsShow");
	}

	public ActionForward moreItemsShow(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :moreItemsShow ");
				
		String	itemFind = "";
		if(request.getParameter("itemFind")!=null) {
			itemFind = ((String)request.getParameter("itemFind"));
			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");
			request.setAttribute("itemFind", itemFind);
		}
		
		String hql = "FROM BCItemBean WHERE code like '%"+itemFind+"%' or name1 like '%"+itemFind+"%'  ORDER BY code";
		new BCAPInvoiceBO().setPage(request, hql);
								
		return mapping.findForward("moreItemsShow");
	}
	
	//ค้นหา เจ้าหนี้
	public ActionForward apFind(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :moreItemsShow ");

		DynaActionForm ap = (DynaActionForm)form;		
		String	itemFind = ap.get("itemFind").toString();
		itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");		//แปลงให้ค้นหาภาษาไทยได้		
		
		request.setAttribute("itemFind", itemFind);		
		
		String hql = "FROM BCAPBean WHERE code like '%"+itemFind+"%' or name1 like '%"+itemFind+"%'  ORDER BY code";
		new BCAPInvoiceBO().setPage(request, hql);
		
		return mapping.findForward("success_apFind");
	}
	
//	//ค้นหา PR=Purchase Request
//	public ActionForward prFind(ActionMapping mapping, ActionForm form,
//			HttpServletRequest request, HttpServletResponse response) 
//			throws Exception {
//		
//		String user 	 = (String)request.getSession().getAttribute("userName");
//		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :moreItemsShow ");
//
//		DynaActionForm pr = (DynaActionForm)form;		
//		String	itemFind = pr.get("itemFind").toString();
//		itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");		//แปลงให้ค้นหาภาษาไทยได้		
//
////		PRFindForm pr = (PRFindForm)form;
////		String itemFind = "";
////		if(pr.getItemFind()!=null) {
////			itemFind = pr.getItemFind(); 
////			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");		//แปลงให้ค้นหาภาษาไทยได้
////		}
//		
//		request.setAttribute("itemFind", itemFind);		
//		
//		String hql = "FROM BCReqConfirmBean WHERE docNo like '%"+itemFind+"%' ORDER BY docNo";
//		new BCAPInvoiceBO().setPage(request, hql);
//		
//		return mapping.findForward("success_prFind");
//	}
	
	@SuppressWarnings("unchecked")
	public ActionForward print(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String docNo = (String)request.getParameter("docNo");
		
		String docNoParam = " i.docNo='" + docNo +"'";
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :print ");		
		System.out.println("#docNo = "+docNo);
				
		String nameOfReport = "/ireport/p23.jasper";			
							
		HashMap hashMap = new HashMap();
		hashMap.put("docNoParam", docNoParam);

		
//		Connection connection;
//		ServletOutputStream servletOutputStream = response.getOutputStream();
//		
//		InputStream reportStream = getServlet().getServletConfig()
//							.getServletContext().getResourceAsStream(nameOfReport);
//		
//		response.setContentType("application/pdf");		
//
//		Class.forName("net.sourceforge.jtds.jdbc.Driver");		
//
//		connection = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.2:1433/ttl51;user=sa;password=admin@123");
//
//		JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, hashMap, connection);
//
//		connection.close();
//		servletOutputStream.flush();
//		servletOutputStream.close();
		if(CommonUtils.runReportToPdf(response, getServlet(), hashMap, nameOfReport)==true) {
			new BCAPInvoiceDAO().addPrintCount(docNoParam);
			System.out.println("run report to pdf: complete");
		}else {
			System.out.println("run Report to pdf: can't run report");
		}
		
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward printContinue(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
				
		String docNoParam = (String)request.getParameter("docNo");
//		String stkDocNoParam = (String)request.getParameter("stkDocNo");
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.print(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceAction #mode :printContinue ");		
		
		
		DynaActionForm dynaForm = (DynaActionForm)form;
		String docNo1 = dynaForm.getString("docNo1");
		String docNo2 = dynaForm.getString("docNo2");
		
		docNoParam = " i.docNo in (";
		
		String[] startDocNo = docNo1.split("-");
		String[] endDocNo = docNo2.split("-");
		String preDocNo = startDocNo[0]+"-"+startDocNo[1]+"-"; 
			
		int countDocNo = Integer.valueOf(endDocNo[2])-Integer.valueOf(startDocNo[2])+1;
		System.out.println("countDocNo = "+countDocNo);
		if(countDocNo>0) {
			for(int i=0; i<countDocNo; i++){
				NumberFormat formatter = new DecimalFormat("0000");
				int docs = (Integer.parseInt(startDocNo[2])+i);
				//System.out.println("docs= "+docs);
				String docs2 = ""+formatter.format(docs);
				docNoParam+="'"+preDocNo+docs2+"',";
			}
			docNoParam = docNoParam.substring(0, docNoParam.length()-1  ) +")";
		}else {
			docNoParam += "'"+docNo1  +"')";
		}
		
		
		System.out.println(docNoParam);

		String nameOfReport= "/ireport/p23.jasper";
		
		HashMap hashMap = new HashMap();
		hashMap.put("docNoParam", docNoParam);
		
//		Connection connection;
//		ServletOutputStream servletOutputStream = response.getOutputStream();
//		
//		InputStream reportStream = getServlet().getServletConfig()
//							.getServletContext().getResourceAsStream(nameOfReport);
//		
//		response.setContentType("application/pdf");		
//		//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//		Class.forName("net.sourceforge.jtds.jdbc.Driver");		
////		connection = DriverManager.getConnection("jdbc:odbc:ttl51","sa","admin@123");
//		connection = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.2:1433/ttl51;user=sa;password=admin@123");
////		System.out.println("connect jTDS ok");
//		JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, hashMap, connection);
//
//		connection.close();
//		servletOutputStream.flush();
//		servletOutputStream.close();
		
		if(CommonUtils.runReportToPdf(response, getServlet(), hashMap, nameOfReport)==true) {
			new BCAPInvoiceDAO().addPrintCount(docNoParam);
			System.out.println("run report to pdf: complete");
		}else {
			System.out.println("run Report to pdf: can't run report");
		}
		
		return null;			
	}
	
	public ActionForward report(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String param = (String)request.getParameter("param");

		if(param==null) {
			return mapping.findForward("report_main");
		}
		
		if(param.equalsIgnoreCase("petty_cash_group")) {
			new BCAPInvoiceReportBO().showPettyCashGroupReport(form, request, response, getServlet());					
		}else if(param.equalsIgnoreCase("petty_cash_summary")) {
			new BCAPInvoiceReportBO().showPettyCashSummaryReport(form, request, response, getServlet());			
		} 		
						
		return null;					
	}
}
